package com.atguigu.jxc.controller;

import com.atguigu.jxc.dao.SaleListDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.CustomerService;
import com.atguigu.jxc.service.UserService;
import com.atguigu.jxc.util.DateUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/saleListGoods")
public class SaleListController {

    @Autowired
    private UserDao userDao;
    @Autowired
    private SaleListDao saleListDao;
    @Autowired
    private CustomerService customerService;
    /**销售单保存
     *http://localhost:8080/saleListGoods/save?saleNumber=XS1605772263999
     */
    @PostMapping("/save")
    @ResponseBody
    public ServiceVO saveSaleList(SaleList saleList, String saleListGoodsStr){
        if (saleList == null || StringUtils.isEmpty(saleListGoodsStr)){
            return null;
        }
        //将字符串转换为集合
        Gson gson = new Gson();
        List<SaleListGoods> saleListGoodsList = gson.fromJson(saleListGoodsStr, new TypeToken<List<SaleListGoods>>() {}.getType());
        //设置当前操作用户
        User user = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        //将用户Id放入
        saleList.setTrueName(user.getTrueName());

        Customer customer = customerService.findById(saleList.getCustomerId());
        saleList.setCustomerName(customer.getCustomerName());

        saleListDao.insertSaleList(saleList);

//        for (SaleListGoods saleListGoods : saleListGoodsList) {
//            saleListGoods.setPurchaseListId(purchaseList.getPurchaseListId());
//
//            saleListDao.insertPurchaseListGoods(purchaseListGoods);
//
//            // 修改商品库存，状态
//            Goods goods = goodsDao.findByGoodsId(purchaseListGoods.getGoodsId());
//
//            goods.setInventoryQuantity(goods.getInventoryQuantity()+purchaseListGoods.getGoodsNum());
//
//            goods.setState(2);
//
//            goodsDao.updateGoods(goods);
//        }
        return new ServiceVO(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    /**销售单查询（可查询条件：销售单号、客户、付款状态）
     *http://localhost:8080/saleListGoods/list
     */
    @PostMapping("/list")
    @ResponseBody
    public Map<String,Object> listSaleGoods(String saleNumber, Integer customerId, Integer state, String sTime,String eTime){
        List<SaleList> saleList = saleListDao.findSaleListGoods(saleNumber,customerId,state,sTime,eTime);
        if(saleList == null){
            return null;
        }
        Map<String,Object> map = new HashMap<String,Object>();
        for (SaleList list : saleList) {
            Customer cus = customerService.findById(list.getCustomerId());
            list.setCustomerName(cus.getCustomerName());
            User user = userDao.getUserById(list.getUserId());
            list.setTrueName(user.getTrueName());

            map.put("rows", list);
        }
        return map;
    }

    /**销售单商品信息
     * http://localhost:8080/saleListGoods/goodsList
     */
    @PostMapping("/goodsList")
    @ResponseBody
    public Map<String,Object> findGoodsList(Integer saleListId){
        List<SaleListGoods> saleListGoodsList = saleListDao.findGoodsList(saleListId);
        if (saleListGoodsList == null){
            return null;
        }
        Map<String,Object> map =new  HashMap<String,Object>();
        map.put("rows", saleListGoodsList);
        return map;
    }

    /**删除销售单
     *http://localhost:8080/saleListGoods/delete
     */
    @PostMapping("/delete")
    @ResponseBody
    public ServiceVO deleteSaleList(Integer saleListId){
        saleListDao.deleteSaliListById(saleListId);

        return new ServiceVO(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    /**客户统计
     *支付结算（修改销售单付款状态）
     * http://localhost:8080/saleListGoods/updateState
     */
    @PostMapping("/updateState")
    @ResponseBody
    public ServiceVO updateState(Integer saleListId){
        saleListDao.updateState(saleListId);

        return new ServiceVO(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    /**商品销售统计
     *销售统计（可根据 商品类别、商品编码或名称 条件查询）
     * http://localhost:8080/saleListGoods/count
     */
    @PostMapping("/count")
    @ResponseBody
    public String count(String sTime, String eTime ,Integer goodsTypeId, String codeOrName){
        List list = saleListDao.count(sTime,eTime,goodsTypeId,codeOrName);
        if(list == null){
            return null;
        }

        return list.toString();
    }

    /**按日统计接口
     *http://localhost:8080/saleListGoods/getSaleDataByDay
     *
     * SELECT
     *     t2.sale_date AS DATE,
     *     SUM( t1.goods_num * t1.price ) AS saleTotal,
     *     SUM( t1.goods_num * t3.purchasing_price ) AS purchasingTotal
     * FROM
     *     t_sale_list_goods t1
     *     LEFT JOIN t_sale_list t2 ON t1.sale_list_id = t2.sale_list_id
     *     LEFT JOIN t_goods t3 ON t1.goods_id = t3.goods_id
     * WHERE
     *     t2.sale_date BETWEEN #{sTime} AND #{eTime}
     * GROUP BY
     *     t2.sale_date
     */
    @PostMapping("/getSaleDataByDay")
    @ResponseBody
    public String getSaleDataByDay(String sTime, String eTime){
        List<SaleData> list = saleListDao.getSaleDateByDay(sTime,eTime);

        if(list == null){
            return null;
        }
        List<String> slotByDay = null;
        try {
            slotByDay = DateUtil.getTimeSlotByDay(sTime, eTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<Map<String,Object>> JsonList = new ArrayList<>();

        Map<String,Object> map = null;

        for (String s : slotByDay) {
            map = new HashMap<>();
            map.put("date", s);
            map.put("saleTotal", 0.0);
            map.put("purchaseingTotal", 0.0);
            map.put("profit",0.0);
            JsonList.add(map);
        }
        for (SaleData saleData : list) {
            map = new HashMap<>();
            map.put("date", saleData.getDate());
            map.put("saleTotal", saleData.getSaleTotal());
            map.put("purchaseingTotal", saleData.getPurchasingTotal());
            map.put("profit", (saleData.getSaleTotal()-saleData.getPurchasingTotal()));
            JsonList.add(map);
        }

        Gson gson = new Gson();
        String s = gson.toJson(JsonList);
        System.out.println("============="+s);
        return s;
    }

    /**按月统计接口
     *http://localhost:8080/saleListGoods/getSaleDataByMonth
     */
    @PostMapping("/getSaleDataByMonth")
    @ResponseBody
    public String getSaleDataByMonth(String sTime, String eTime) throws Exception {
        List<SaleData> list = saleListDao.getSaleDataByMonth(sTime,eTime);
        if(list == null){
            return null;
        }


        List<String> slotByDay = DateUtil.getTimeSlotByDay(sTime, eTime);
        List<Map<String,Object>> JsonList = new ArrayList<>();

        for (String s : slotByDay) {
            for (SaleData saleData : list) {
                Map<String,Object> map = new HashMap<>();
                if(s.equals(saleData.getDate())){
                    map.put("date", saleData.getDate());
                    map.put("saleTotal", saleData.getSaleTotal());
                    map.put("purchaseingTotal", saleData.getPurchasingTotal());
                    map.put("profit", (saleData.getSaleTotal()-saleData.getPurchasingTotal()));
                }else {
                    map.put("date", s);
                    map.put("saleTotal", 0);
                    map.put("purchaseingTotal", 0);
                    map.put("profit", 0);
                }

                JsonList.add(map);
            }
        }


        Gson gson = new Gson();
        String s = gson.toJson(JsonList);
        System.out.println("============="+s);
        return s;
    }
}
